package com.bckj.fastboot.iot.mq.redis.delaymsg;

import com.bckj.fastboot.core.jackson.JsonUtils;
import com.bckj.fastboot.iot.common.dto.request.MessageRecordRequest;
import com.bckj.fastboot.iot.common.repository.MessageRecordRepository;
import com.bckj.fastboot.iot.mq.redis.constants.RedisMQConstants;
import com.bckj.fastboot.iot.mq.redis.model.DelayedMessage;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class DelayedMessageSender {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private MessageRecordRepository messageRecordRepository;

    /**
     * 发送一个延时消息
     * @param topic 消息主题，如 "order_timeout"
     * @param payload 消息内容，如订单ID
     * @param delay 延时时间
     * @param timeUnit 延时单位
     */
    public void sendDelayedMessage(String topic, String payload, long delay, TimeUnit timeUnit) {
        long executeTime = Instant.now().toEpochMilli() + timeUnit.toMillis(delay);
        String messageId = UUID.randomUUID().toString();
        DelayedMessage message = new DelayedMessage();
        message.setId(messageId);
        message.setTopic(topic);
        message.setPayload(payload);
        message.setExecuteTime(executeTime);
        // 序列化消息（可优化为 JSON）
        String value = JsonUtils.toJsonStr(message);

        // 存入 Redis ZSET，score 是执行时间戳
        redisTemplate.opsForZSet().add(RedisMQConstants.DELAYED_MESSAGES_ZSET_KEY, value, executeTime);
        saveMessageRecord(message);
    }

    @Async
    public void saveMessageRecord(DelayedMessage message) {
        var request = new MessageRecordRequest();
        request.setMsgId(message.getId());
        request.setTopic(message.getTopic());
        request.setPayload(message.getPayload());
        messageRecordRepository.save(request);
    }
}